package com.mall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.mall.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录信息
        String id = request.getHeader("id");
        //判断是否获取了用户，如果有，存入ThreadLocal
        if (StrUtil.isNotBlank(id)){
            UserContext.setUser(Long.valueOf(id));
        }
        //3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理用户
        UserContext.removeUser();
    }
}
